def KSA(key):
    """密钥调度算法 (Key Scheduling Algorithm)"""
    key_length = len(key)
    state = list(range(256))
    j = 0
    for i in range(256):
        j = (j + state[i] + key[i % key_length]) % 256
        state[i], state[j] = state[j], state[i]
    return state

def PRGA(state):
    """伪随机数生成算法 (Pseudo-Random Generation Algorithm)"""
    i = 0
    j = 0
    keystream = []
    for _ in range(256):
        i = (i + 1) % 256
        j = (j + state[i]) % 256
        state[i], state[j] = state[j], state[i]
        K = state[(state[i] + state[j]) % 256]
        keystream.append(K)
    return keystream

def RC4(key, plaintext):
    """RC4 加密函数
    注意：RC4 算法存在已知的安全漏洞，建议使用更安全的加密算法，如 AES。
    """
    state = KSA(key)
    keystream = PRGA(state)
    ciphertext = bytearray()
    for byte, k in zip(plaintext, keystream):
        encrypted_byte = byte ^ k
        ciphertext.append(encrypted_byte)
    return bytes(ciphertext)

def main():
    try:
        key = input("请输入密钥: ").encode('utf-8')
        if not key:
            raise ValueError("密钥不能为空")
        if len(key) > 256:
            raise ValueError("密钥长度不能超过256字节")

        plaintext = input("请输入明文: ").encode('utf-8')
        if not plaintext:
            raise ValueError("明文不能为空")

        # 加密
        ciphertext = RC4(key, plaintext)
        print(f"加密后的密文 (十六进制): {ciphertext.hex()}")
    except ValueError as e:
        print(f"错误: {e}")
    except Exception as e:
            print(f"未知错误: {e}")

if __name__ == "__main__":
        main()